// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod app;
mod entity;
mod response;
mod routes;
mod sqlite;
mod ssh;
mod system_menu;

use entity::structs::MyMessage;
use std::sync::Arc;
//use std::sync::Mutex;
use tauri::menu;
use tauri::menu::CheckMenuItem;
use tauri::menu::IconMenuItem;
use tauri::menu::Menu;
use tauri::menu::MenuItem;
use tauri::menu::{CheckMenuItemBuilder, MenuBuilder, MenuItemBuilder, Submenu, SubmenuBuilder};
use tokio::sync::Mutex;
//use tauri::tray::{ClickType, TrayIconBuilder};
use tauri::tray::TrayIconBuilder;
use tauri::tray::TrayIconEvent;
use tauri::App;
use tauri::AppHandle;
use tauri::Manager;
use tauri::WebviewWindowBuilder;
use tauri_plugin_autostart::MacosLauncher;
use tauri_plugin_autostart::ManagerExt;

use crate::app::app::{init_app_dir, APP};
use crate::routes::app_window::{
    about, loding_window_close, windows_center, windows_close, windows_hide, windows_maximize,
    windows_minimize, windows_unmaximize,
};
use crate::sqlite::sqlite::init_table;
use sqlite::app_setting::{
    get_auto_start_state, query_setting_item, query_setting_list, updatate_setting,
};
use sqlite::ssh_connection::{
    connection_create, connection_delete, connection_edit, connection_list,
};
use tokio::sync::{mpsc, oneshot};

use crate::ssh::ssh_control::accept_connection;
use crate::ssh::ssh_control::SshManager;

// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

fn show_window(app: &AppHandle) {
    let windows = app.webview_windows();

    windows
        .values()
        .next()
        .expect("Sorry, no window found")
        .set_focus()
        .expect("Can't Bring Window to Focus");
}

#[macro_use]
extern crate log;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate rusqlite;
#[macro_use]
extern crate anyhow;
#[tokio::main]
async fn main() {
    // println!("服务启动成功,端口:5555");
    let listener = tokio::net::TcpListener::bind("127.0.0.1:5555")
        .await
        .unwrap();
    println!("Server started on ws://127.0.0.1:5555");
    // setup channel
    let (tx_from_ws, mut rx_from_ws) = mpsc::channel::<String>(32);

    // print all messages received from websocket
    tokio::spawn(async move {
        while let Some(msg) = rx_from_ws.recv().await {
            println!("通道收到消息 websocket: {}", msg);
        }
    });
    let ssh_manager = Arc::new(Mutex::new(SshManager::new()));
    //let (tx, _rx) = tokio::sync::broadcast::channel(1024);
    tokio::spawn(async move {
        while let Ok((stream, _)) = listener.accept().await {
            let peer = stream
                .peer_addr()
                .expect("connected streams should have a peer address");
            println!("端口地址 address: {}", peer);
            let ssh_manager_clone = Arc::clone(&ssh_manager);
            tokio::spawn(accept_connection(
                peer,
                stream,
                tx_from_ws.clone(),
                ssh_manager_clone,
            ));
        }
    });
    let _app = tauri::Builder::default()
        .plugin(tauri_plugin_dialog::init())
        .plugin(tauri_plugin_shell::init())
        .plugin(tauri_plugin_notification::init())
        .plugin(tauri_plugin_autostart::init(
            MacosLauncher::LaunchAgent,
            Some(vec!["--flag1", "--flag2"]),
        ))
        .plugin(tauri_plugin_single_instance::init(|app, args, cwd| {
            let _ = show_window(app);
        }))
        .setup(move |app: &mut App| {
            let handle = app.handle();
            APP.lock().update_app_dir(&handle);
            init_app_dir();
            init_table();

            //托盘图标菜单
            let about = MenuItemBuilder::with_id("about", "关于").build(app)?;
            let quit = MenuItemBuilder::with_id("quit", "退出").build(app)?;
            let show = MenuItemBuilder::with_id("show", "显示").build(app)?;
            let menu2 = MenuBuilder::new(app)
                .items(&[&show, &about, &quit])
                .build()?;
            let tray = TrayIconBuilder::new()
                .menu(&menu2)
                .on_menu_event(move |app, event| match event.id().as_ref() {
                    "about" => {
                        println!("关于");
                    }
                    "quit" => {
                        let tary_ = app.get_webview_window("main").unwrap();
                        println!("退出");
                        tary_.close().unwrap();
                    }
                    "show" => {
                        let tary_ = app.get_webview_window("main").unwrap();
                        println!("show");
                        tary_.show().unwrap();
                    }
                    _ => (),
                })
                .on_tray_icon_event(|tray, event| match event {
                    // 具体处理某些事件
                    TrayIconEvent::Click { .. } => {
                        // 处理右键点击事件
                        println!("托盘图标Click");
                    }
                    TrayIconEvent::DoubleClick { .. } => {
                        println!("托盘图标DoubleClick");
                        let app = tray.app_handle();
                        if let Some(webview_window) = app.get_webview_window("main") {
                            let _1 = webview_window.show();
                            let _2 = webview_window.set_focus();
                            //let _3 = webview_window.set_always_on_top(true);
                        }
                    }
                    TrayIconEvent::Enter { .. } => {
                        // 处理右键点击事件
                        println!("托盘图标Enter");
                    }
                    TrayIconEvent::Move { .. } => {
                        // 处理右键点击事件
                        //println!("托盘图标Move");
                    }
                    TrayIconEvent::Leave { .. } => {
                        // 处理右键点击事件
                        //println!("托盘图标Leave");
                    }
                    // 添加默认匹配项来处理所有其他未列出的事件
                    _ => {
                        println!("托盘图标");
                    }
                })
                .icon(app.default_window_icon().cloned().unwrap())
                .tooltip("你好，爹地".to_string())
                .title("hello,Baby")
                .build(app)?;

            // if event. == ClickType::Left {
            //     let app = tray.app_handle();
            //     if let Some(webview_window) = app.get_webview_window("main") {
            //         let _ = webview_window.show();
            //         let _ = webview_window.set_focus();
            //     }
            // }
            // let ev=event.id();
            // if ev=="left"{
            //     let app = tray.app_handle();
            //     if let Some(webview_window) = app.get_webview_window("main") {
            //         let _ = webview_window.show();
            //         let _ = webview_window.set_focus();
            //     }
            // }

            //main  窗口
            let win_builder = WebviewWindowBuilder::new(
                app,
                "main".to_string(),
                tauri::WebviewUrl::App("/".into()),
            )
            .title("Hello, Baby")
            .inner_size(970.0, 590.0)
            .visible(true)
            .min_inner_size(970.0, 590.0)
            .resizable(true)
            .transparent(true)
            .decorations(false)
            .center()
            .shadow(true)
            .on_page_load(|window, _| {
                window.set_focus().unwrap();
            })
            .build()
            .unwrap();

            // // Get the autostart manager
            // let autostart_manager = app.autolaunch();
            // // 启用 autostart
            // if(get_auto_start_state()){
            //     let _ = autostart_manager.enable();
            //       // 检查 enable 状态
            //     println!(
            //         "检查 enable 状态 registered for autostart? {}",
            //         autostart_manager.is_enabled().unwrap()
            //     );
            // }else{
            //     // 禁用 autostart
            //     let _ = autostart_manager.disable();
            // }

            //菜单
            let menu = Menu::new(app)?;
            let submenu = SubmenuBuilder::new(handle, "文件(F)")
                .item(&MenuItem::new(handle, "MenuItem 1", true, None::<&str>)?)
                .items(&[
                    &CheckMenuItem::new(handle, "CheckMenuItem 1", true, true, None::<&str>)?,
                    &IconMenuItem::new(
                        handle,
                        "IconMenuItem 1",
                        true,
                        Some(app.default_window_icon().cloned().unwrap()),
                        None::<&str>,
                    )?,
                ])
                .separator()
                .cut()
                .copy()
                .paste()
                .separator()
                .text("item2", "MenuItem 2")
                .check("checkitem2", "CheckMenuItem 2")
                .separator()
                .icon(
                    "iconitem3",
                    "退出",
                    app.default_window_icon().cloned().unwrap(),
                )
                .build()?;
            menu.append(&submenu)?;

            //app.set_menu(menu)?;

            app.on_menu_event(move |app, event| {
                if event.id() == "check" {
                    println!("`check` triggered, do something! is checked? ");
                } else if event.id() == "toggle" {
                    println!("toggle triggered!");
                }
            });
            Ok(())
        })
        .invoke_handler(tauri::generate_handler![
            greet,
            windows_minimize,
            windows_hide,
            windows_maximize,
            windows_unmaximize,
            windows_center,
            windows_center,
            windows_close,
            query_setting_list,
            updatate_setting,
            query_setting_item,
            connection_create,
            connection_delete,
            connection_edit,
            connection_list
        ])
        //.menu(f)
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
